#pragma once

#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <functional>
// #include <netinet/in.h>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Mythread.hpp"

using namespace Mythread;
enum
{
	SOCKET_ERROR = 1,
	BIND_ERROR,
	LISTEN_ERROR,
	USAGE_ERROR
};

const static int d_listensock = -1;
const static int d_backlog = 16;

// using task_t = std::function<void()>;
using task_t = std::function<std::string(const std::string &)>;
class Tcpserver;

class ThreadData
{
public:
	ThreadData(int fd, InetAddr addr, Tcpserver *s) : sockfd(fd), clientaddr(addr), self(s)
	{
	}

public:
	int sockfd;
	InetAddr clientaddr;
	Tcpserver *self;
};

class Tcpserver
{
public:
	Tcpserver(int port, task_t func)
		: _port(port),
		  _listensock(d_listensock),
		  _isrunning(false),
		  _func(func)
	{
	}

	void Initserver()
	{
		// 1.创建字符流式套接字
		_listensock = socket(AF_INET, SOCK_STREAM, 0);
		if (_listensock < 0)
		{
			LOG(FATAL, "socket error");
			exit(SOCKET_ERROR);
		}

		LOG(DEBUG, "socket create success, sockfd is : %d\n", _listensock);

		// 2.bind
		// 先填充socket_in结构
		struct sockaddr_in saddr;
		memset(&saddr, 0, sizeof(saddr));
		saddr.sin_family = AF_INET;
		saddr.sin_port = htons(_port);
		saddr.sin_addr.s_addr = INADDR_ANY;

		int r = ::bind(_listensock, (struct sockaddr *)&saddr, sizeof(saddr));
		if (r < 0)
		{
			LOG(FATAL, "bind error");
			exit(BIND_ERROR);
		}

		LOG(DEBUG, "bind success, sockfd is : %d\n", _listensock);

		// 3. tcp是面向连接的，所以通信之前，必须先建立连接。服务器是被连接的
		//    tcpserver 启动，未来首先要一直等待客户的连接到来
		r = ::listen(_listensock, d_backlog);
		if (r < 0)
		{
			LOG(FATAL, "listen error");
			exit(LISTEN_ERROR);
		}

		LOG(DEBUG, "listen success, sockfd is : %d\n", _listensock);
	}

	// 这里是一个echo服务任务
	void Service(int sockfd, InetAddr client) // 想知道是谁给服务器发送
	{
		LOG(DEBUG, "get a new link, info %s:%d, fd : %d\n", client.ip().c_str(), client.port(), sockfd);

		std::string clientaddr = "[" + client.ip() + ":" + std::to_string(client.port()) + "]#";
		while (true)
		{
			char inbuffer[1024];
			// 这里是因为建立了文件描述符连接，所有不需要再在网络上发送和接收消息，所以不需要用到recvfrom和sendto
			ssize_t r = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
			// ssize_t r = read(sockfd, inbuffer, sizeof(inbuffer) - 1);
			if (r > 0)
			{
				inbuffer[r] = 0;
				std::cout << clientaddr << inbuffer << std::endl;

				std::string result = _func(inbuffer);

				send(sockfd, result.c_str(), result.size(), 0);
			}
			else if (r == 0)
			{
				// client 退出&&关闭连接了
				LOG(INFO, "%s quit\n", clientaddr.c_str());
				break;
			}
			else
			{
				LOG(ERROR, "read error\n", clientaddr.c_str());
				break;
			}
		}

		::close(sockfd); // 文件描述符泄漏
	}

	static void *HandlerSock(void *args)
	{
		pthread_detach(pthread_self());
		ThreadData *td = static_cast<ThreadData *>(args);
		td->self->Service(td->sockfd, td->clientaddr);
		delete td;
		return nullptr;
	}
	void Loop()
	{
		_isrunning = true;
		// 4.TCP与UDP的区别就在于TCP不能直接接收数据，先获取连接
		while (_isrunning)
		{
			struct sockaddr_in peer;
			socklen_t len = sizeof(peer);
			int sockfd = ::accept(_listensock, (struct sockaddr *)&peer, &len);
			if (sockfd < 0)
			{
				LOG(WARNING, "accept error\n");
				continue;
			}		
			// Version 2 : 采用多线程
			// 所以综合多线程分离处理模式更优
			pthread_t pth;
			ThreadData *td = new ThreadData(sockfd, InetAddr(peer), this);
			pthread_create(&pth, nullptr, HandlerSock, td);
		}

		_isrunning = false;
	}

	~Tcpserver()
	{
		if (_listensock > d_listensock)
			::close(_listensock);
	}

private:
	int _port;		 // 端口号
	int _listensock; // 监听文件描述符
	bool _isrunning; // 是否服务

	task_t _func;
};